﻿using Microsoft.EntityFrameworkCore.Metadata;
using System.Reflection;

namespace Microsoft.EntityFrameworkCore;
public static class EntityFrameworkCoreExtensions
{
    public static string GetColumnName(this PropertyEntry entry)
    {
        var columnName = entry.Metadata.Name;

        if (columnName.EndsWith("Id"))
        {
            if (entry.Metadata.IsForeignKey() && entry.Metadata.IsShadowProperty())
            {
                columnName = columnName[..^2];
            }
        }

        return columnName;
    }

    public static string? GetDisplayName(this PropertyEntry entry, string propName)
    {
        var type = entry.EntityEntry.Metadata.ClrType;

        var prop = type.GetProperty(propName);

        if (prop is null)
        {
            return null;
        }

        var attr = prop.GetCustomAttribute<DisplayNameAttribute>(true);

        return attr?.DisplayName;
    }

    public static bool TryGetPrincipalTable(this PropertyEntry entry, out IEntityType? entityType)
    {
        entityType = null;

        try
        {
            entityType = entry.Metadata.GetContainingForeignKeys().ToArray()[0].PrincipalEntityType;

            return true;
        }
        catch
        {
            return false;
        }
    }

    public static string GetDisplayName(this IEntityType entityType)
    {
        var attr = entityType.ClrType.GetCustomAttribute<DisplayNameAttribute>();

        return attr is null ? entityType.ClrType.Name : attr.DisplayName;
    }

    public static string GetDisplayName(this EntityEntry entry)
    {
        var attr = entry.Metadata.ClrType.GetCustomAttribute<DisplayNameAttribute>();

        return attr is null ? entry.Metadata.GetTableName()! : attr.DisplayName;
    }
}